<template>
  <div>
    <!-- <el-button @click="showDialog" type="primary" icon="el-icon-plus" style="margin-top: 20px"
      >添加</el-button
    > -->


    <el-table :data="proList" border style="width: 100%; margin-top: 40px">
      <el-table-column type ="index" label="ID" width="80" align="center">
      </el-table-column>
      <el-table-column prop="name" label="物品名称" align="center">
      </el-table-column>
      <el-table-column prop="picture" label="图片" width="180" align="center" >
        <template slot-scope="{ row }">
          <img :src="`http://lfmini.hxcraft.top`+row.picture" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      
      <el-table-column prop="location" label="物品丢失地点" align="center">
      </el-table-column>
      <el-table-column prop="resType" label="物品状态" align="center">
        <template slot-scope="{ row: {resType}} ">
          <span v-if="+resType ==1" >寻失主</span>
          <span v-else-if="+resType ==0">寻物品</span>
          <span v-else>已完成</span>
        </template>
      </el-table-column>
      <el-table-column pro="" label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" @click="showDialog(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteu(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 
        
     -->
    <el-pagination
      style="text-align: center; margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[2, 3, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,total,sizes"
      :total="total"
    >
    </el-pagination>

    <!-- 表单 -->
    <el-dialog :title="proForm.userId ? '修改物品' : '添加物品'" 
    style="width:100"
    :visible.sync="dialogFormVisible"
    :before-close="close">
      <el-form :model="proForm" ref="addForm" >
        <el-form-item label="物品名称" label-width="100px" prop ="name">
          <el-input v-model="proForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="物品图片" label-width="100px" prop = "picture">
          <el-upload
            class="avatar-uploader"
            action="https://lfcon.hxcraft.top/service_manage/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          
            :before-upload="beforeAvatarUpload">
            <img v-if="proForm.picture" :src="`http://lfmini.hxcraft.top`+proForm.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload_tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <!-- <el-upload
          class="upload-demo"
          action="#"
          ref="upload"
          :multiple="true"
          accept="image/jpeg,image/jpg,image/png"
          :auto-upload="false"
          :on-preview="handlePreview"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :file-list="fileList"
          list-type="picture-card">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog> -->
        </el-form-item>
        <el-form-item label="物品丢失地点" label-width="100px" prop ="location">
          <el-input v-model="proForm.location" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="物品状态" label-width="100px" prop="resType" >
          <el-radio-group v-model="proForm.resType">
              <el-radio :label=1 v-model="proForm.resType">失物招领</el-radio>
              <el-radio :label=0 v-model="proForm.resType">寻物启事</el-radio>
              <el-radio :label=-1 v-model="proForm.resType">已完成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="concel">取 消</el-button>
        <el-button type="primary" @click="save()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken}  from "@/utils/auth";
export default {
  name: "proList",
  data() {
    return {
      page: 1,
      limit: 10,
      total: 15,
      // productList:[],
      dialogFormVisible:false,
      proForm:{
        userId:"",
        name:"",
        location:"",
        picture:"",
        resType:1,
      },
      proList:[]
    }
  },
  mounted(){
    this.getProductList(this.page)
  },
  methods:{
        showDialog(row){
              //该函数添加属性和编辑属性都会调用
              //编辑属性的时候会传入row（当前行的数据对象）
              //通过id属性判断当前回调函数的触发来源
              if(row.userId){
                //只有编辑才能进入该区域
                //此处是引用值传递
                //...是浅拷贝，将当前row对象中的所有属性以及他们的值复制一份到tmForm中
                // alert(row.resType)
                this.proForm = {
                  ...row
                };

              }
                this.dialogFormVisible = true
        },
        //物品分页
        async getProductList(page){
              const {
                data: { total, items },
            } = await this.$API.productlist.getProductList(getToken(),page ? page : this.page, this.limit);
            this.total = total;
            if(page){
              this.page = page
            }
            // console.log(result);
            this.proList = items;
        },
        //
        close(){
          this.dialogFormVisible=false,
          this.proForm={
            userId:"",
            name:"",
            location:"",
            picture:"",
            resType:1,
          }
        },

        // 点击第几页
        handleCurrentChange(value) {
        //通过当前事件，可以知道用户点击了哪个页数
        this.page = value;
        //发送请求，获取对应页面的数据
        this.getProductList(this.page);
        },

        //限制当前页面显示的数量
        handleSizeChange(value) {
        this.limit = value;
        this.getProductList(this.page);
        },

        handleAvatarSuccess(res) {
            //由于用户通过input标签选中图片后，该图片就存储于浏览器内存中
            //以下代码是将内存中的图片，生成本地链接地址，用来展示
            // this.imageUrl = URL.createObjectURL(file.raw);\
            this.proForm.picture =res.data[0].url;
            
            // alert(this.proForm.picture)
            
            
        },

        beforeAvatarUpload(file) {
            const types = ['image/jpeg','image/jpg','image/png'];
            const isJPG = types.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        save(){
          //首先先校验数据的合法信
            this.$refs.addForm.validate(async(valid)  => {
            //valid代表表单的全部校验结果
            if (valid) {
              //1、收集请求所需要的数据
              //已经整理在userForm中，不需要在收集
              // alert(1)
              this.proForm.resType =  Number(this.proForm.resType)
              try {
                    //2.发送请求
                    
                    await this.$API.productlist.addOrUpdate(getToken(),this.proForm);
                    // console.log(this.proForm);
                    // alert(1)
                    //请求最新的品牌列表，由于添加功能无法知道在那一页，所以统一请求第一页
                    this.getProductList(this.page);
                    //弹窗提示
                    //3.成功之后
                    // if(row.id){
                    //   this.$message({
                    //     message:'修改成功',
                    //     type:'success'
                    //   })
                    // }
                    this.$message({
                        message:'修改成功',
                        type: 'success'
                    });
                    //将添加框隐藏
                    this.dialogFormVisible = false
                    //清空当前dialog的内容
                    this.proForm = {
                      userId:"",
                      name:"",
                      location:"",
                      picture:"",
                      resType:1,
                    }
                } catch (error) {
                  //4.失败之后
                    this.$message({
                        message: '修改失败',
                        type: 'info'
                    });
                   
                } 
            } else {
               this.dialogFormVisible = false
            //this.$message.info("保存失败")
            }
          });
           
        },

        concel(){
          this.dialogFormVisible = false
          this.proForm = {
            userId:"",
            name:"",
            location:"",
            picture:"",
            resType:1,
         }
        },

        deleteu(row) {
        // alert(row.id)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          //点击确定之后执行的代码
          //发送请求 
          try {
            //1.发送请求
              await this.$API.productlist.deletePro(getToken(),row.id);
              this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //请求最新列表
            //如果当前页面还有数据就请求当前页面
            //如果删除的是当前页面的最后一个数据则请求前一个夜间

            this.getProductList(this.proList.length>1? this.page : this.page-1);
          } catch (error) {
              this.$message({
              type: 'info',
              message: '删除失败'
            });
          }   
        }).catch(() => {
            this.$message({
            type: 'info',
            message: '已取消删除'
          });        
        });
      }
  }
};
</script>
  
<style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>